// pages/address/wph-address/wph-address.js
var cityDataList = require('../../../data/cityList').cityList;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    birthday: '2020-02-02',
    provinceList: [],
    provinceDTO: {},
    cityList: [],
    cityDTO: {},
    countyList: [],
    countyDTO: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getProvinceList()
  },

  /**
   * 省份
   */
  getProvinceList() {
    let provinceList = [];
    provinceList.push({
      name: "请选择省份"
    });
    cityDataList.forEach((item) => {
      provinceList.push({
        name: item.name
      });
    });

    this.setData({
      provinceList: provinceList,
    });
  },

  // 地址选择
  addressChange: function (e) {
    var type = e.currentTarget.dataset.type
    var index = e.detail.value
    if (type == 'province') { // 省份
      var provinceDTO = this.data.provinceList[index]
      let cityList = [];
      cityList.push({
        name: "请选择城市"
      });
      cityDataList.forEach((item) => {
        if (item.name == provinceDTO.name) {
          item.city.forEach((item, index) => {
            cityList.push({
              name: item.name
            });
          });
        }
      });

      if (this.data.provinceDTO.name && provinceDTO.name != this.data.provinceDTO.name) {
        this.setData({
          provinceDTO: provinceDTO,
          cityDTO: {},
          countyDTO: {},
          cityList: cityList,
          countyList: [],
        });
      } else {
        this.setData({
          provinceDTO: provinceDTO,
          cityList: cityList,
        });
      }


    } else if (type == 'city') {
      var cityDTO = this.data.cityList[index]
      let countyList = [];
      countyList.push({
        name: "请选择区县"
      });
      cityDataList.forEach((item) => {
        if (item.name == this.data.provinceDTO.name) {
          item.city.forEach((item, index) => {
            if (item.name == cityDTO.name) {
              item.area.forEach((item) => {
                countyList.push({
                  name: item.name
                });
              });
            }
          });
        }
      });

      if (this.data.cityDTO.name && cityDTO.name != this.data.cityDTO.name) {
        this.setData({
          countyDTO: {},
          countyList: countyList,
        });
      } else {
        this.setData({
          cityDTO: cityDTO,
          countyList: countyList,
        });
      }
    } else if (type == 'county') {
      var countyDTO = this.data.countyList[index]
      this.setData({
        countyDTO: countyDTO
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

})